<template>
  <a-drawer width="35%" :label-col="4" :wrapper-col="14" :visible="open" @close="onClose">
    <a-divider orientation="left">
      <b>{{ formTitle }}</b>
    </a-divider>
    <a-form-model ref="form" :model="form" :rules="rules">
      <a-form-model-item label="订单编码/订单合同号" prop="orderCode">
        <a-input v-model="this.order.orderCode" disabled />
      </a-form-model-item>
      <a-form-model-item
        label="产品"
        prop="productId"
        v-show="this.form.orderProductId === undefined"
      >
        <a-select
          class="number-border"
          show-search
          placeholder="请输入产品编号或名称"
          :default-active-first-option="false"
          :show-arrow="false"
          :filter-option="false"
          :not-found-content="null"
          :value="this.form.productId"
          @change="handleChange"
          @search="handleSearch"
        >
          <a-select-option
            v-for="d in productData"
            :key="d.productId"
          >{{ d.productCode }}/{{ d.productName }}</a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-model-item
        label="产品"
        prop="productId"
        v-show="this.form.orderProductId !== undefined"
      >
        <a-input v-model="this.productCodeAndName" disabled />
      </a-form-model-item>
      <a-form-model-item label="库存" prop="storage">
        <a-input v-model="storage" disabled />
      </a-form-model-item>
      <a-form-model-item label="预定数量" prop="productNum" class="number">
        <a-input-number v-model="form.productNum" class="number-border" />
      </a-form-model-item>
      <a-form-model-item label="实际数量" prop="actualNum" class="number">
        <a-input-number v-model="form.actualNum" class="number-border" @change="changeTotal" />
      </a-form-model-item>
      <a-form-model-item label="产品单价" prop="productPrice" class="number">
        <a-input-number
          v-model="form.productPrice"
          @change="changeTotal"
          class="number-border"
          :formatter="value => `￥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
          :parser="value => value.replace(/\￥\s?|(,*)/g, '')"
        />
      </a-form-model-item>
      <a-form-model-item label="实际总价" prop="totalPrice" class="number">
        <a-input-number
          v-model="form.totalPrice"
          class="number-border"
          :formatter="value => `￥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
          :parser="value => value.replace(/\￥\s?|(,*)/g, '')"
        />
      </a-form-model-item>
      <a-form-model-item label="订单货期" prop="deliveryTime" class="number">
        <a-date-picker
          show-time
          type="date"
          v-model="form.deliveryTime"
          class="number-border"
          format="YYYY-MM-DD HH:mm:ss"
          valueFormat="YYYY-MM-DD HH:mm:ss"
        />
      </a-form-model-item>
      <a-form-model-item label="完工时间" prop="finishTime" class="number">
        <a-date-picker
          show-time
          type="date"
          v-model="form.finishTime"
          class="number-border"
          format="YYYY-MM-DD HH:mm"
          valueFormat="YYYY-MM-DD HH:mm:ss"
        />
      </a-form-model-item>
      <a-form-model-item label="备注" prop="remark">
        <a-input v-model="form.remark" placeholder="请输入" type="textarea" allow-clear />
      </a-form-model-item>
      <div class="bottom-control">
        <a-space>
          <a-button type="primary" @click="submitForm">保存</a-button>
          <a-button type="dashed" @click="cancel">取消</a-button>
        </a-space>
      </div>
    </a-form-model>
  </a-drawer>
</template>

<script>
import { getByCodeOrName, selectStorage } from '@/api/erp/product'
import { addOrderProduct, getOrderProduct, updateOrderProduct } from '@/api/erp/orderProduct'

export default {
  name: 'CreateDataForm',
  data () {
    const storageCheck = (rule, value, callback) => {
      if (value < 0) {
        callback(new Error('不能为负数'))
      } else if (this.storage < 0) {
        callback(new Error('库存不足'))
      } else {
        callback()
      }
    }
    const checkNum = (rule, value, callback) => {
      if (value < 0) {
        callback(new Error('不能为负数'))
      } else {
        callback()
      }
    }
    return {
      open: false,
      formTitle: '',
      form: {
        productNum: 0,
        actualNum: 0,
        productPrice: 0,
        totalPrice: 0,
        deliveryTime: undefined,
        finishTime: undefined,
        productId: undefined,
        orderId: undefined,
        remark: undefined
      },
      rules: {
        productId: [
          { required: true, message: '产品不能为空', trigger: 'blur' }
        ],
        actualNum: [
          { trigger: 'change', validator: storageCheck }
        ],
        productNum: [
          { trigger: 'change', validator: checkNum }
        ],
        productPrice: [
          { trigger: 'change', validator: checkNum }
        ],
        totalPrice: [
          { trigger: 'change', validator: checkNum }
        ]
      },
      order: {},
      productData: [],
      productCodeAndName: undefined,
      storage: 0,
      totalNum: 0
    }
  },
  methods: {
    onClose () {
      this.open = false
    },
    /** 新增按钮操作 */
    handleAdd (orderRecord) {
      this.reset()
      this.productData = []
      this.order = orderRecord
      this.form.orderId = orderRecord.orderId
      this.formTitle = '订单' + this.order.orderCode + '添加产品'
      this.open = true
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.reset()
      this.productData = []
      getOrderProduct(row.orderProductId).then(response => {
        const orderProduct = response.data
        this.order.orderCode = orderProduct.orderCode
        this.form = orderProduct
        this.productCodeAndName = orderProduct.productCode + '/' + orderProduct.productName
        this.getStorage(orderProduct.productId)
        this.open = true
      })
    },
    handleChange (value) {
      this.form.productId = value
      this.getStorage(value)
    },
    handleSearch (value) {
      const data = { name: value }
      getByCodeOrName(data).then(response => {
        this.productData = response.data
      })
    },
    reset () {
      this.form = {
        productNum: 0,
        actualNum: 0,
        productPrice: 0,
        totalPrice: 0,
        deliveryTime: undefined,
        finishTime: undefined,
        productId: undefined,
        orderId: undefined
      }
      this.productData = []
    },
    submitForm () {
      if (this.form.orderProductId !== undefined) {
        updateOrderProduct(this.form).then(response => {
          this.$message.success(
            '修改成功',
            3
          )
          this.open = false
          this.$emit('ok')
        })
      } else {
        this.$refs.form.validate(valid => {
          if (valid) {
            addOrderProduct(this.form).then(response => {
              this.$message.success(
                '新增成功',
                3
              )
              this.open = false
              this.$emit('ok')
            })
          }
        })
      }
    },
    cancel () {
      this.open = false
      this.reset()
    },
    changeTotal (e) {
      this.storage = this.totalNum - this.form.actualNum
      this.form.totalPrice = this.form.actualNum * this.form.productPrice
    },
    getStorage (productId) {
      selectStorage(productId).then(response => {
        this.totalNum = response.data + this.form.actualNum
        this.storage = this.totalNum - this.form.actualNum
      })
    }
  }
}
</script>

<style lang="less" scoped>
.number {
  display: inline-block;
  width: calc(~"50% - 12px");
}
.number-border {
  width: calc(~"100% - 12px");
}
</style>
